#coding=utf-8
#LightCam 日志监控程序
#init by hfh 20150212

#import multiprocessing,subprocess
import socket,os,time,re,traceback,subprocess,sys
import lc_libs

def LCSybase_count(Identifier):
	popen=subprocess.Popen(isql,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
	popen.stdin.write("select count(*) from status where Identifier='%s'\n" % Identifier)
	popen.stdin.write("go\n")
	popen.stdin.write("exit\n")
	res=""
	for line in popen.stdout.read().split('\n'):
		if "COUNT" in line or "-----" in line or "affected" in line:
			continue
		else:
			res=line.strip('\r\n ')
	if res=="":
		res="0"
	return res
	
def LCSybase_update(sql):
	popen=subprocess.Popen(isql,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
	popen.stdin.write(sql+"\n")
	popen.stdin.write("go\n")
	popen.stdin.write("exit\n")
	res=""
	res=popen.stdout.read()
#	for line in popen.stdout.read().split('\n'):
##		if "affected" in line:
#			res=res+line.strip('\r\n (').split(' ')[0]
	return res

def func(ServerName,SyslogFile):
	file=open(SyslogFile,'r')
	file.readlines()
	while True:
		#执行日志监控
		filecontent=file.readline().strip('\r\n')
		if str(filecontent) == "":
			time.sleep(1)
			continue
		if "LightCam" not in filecontent:
			continue
		res=re.findall(r"Node:(.*) AlertGroup",filecontent,re.S)
		if len(res) <> 0:
			Node=res[0].upper()
		res=re.findall(r"AlertGroup:(.*) AlertKey",filecontent,re.S)
		if len(res) <> 0:
			AlertGroup=res[0]
		res=re.findall(r"AlertKey:(.*) Severity",filecontent,re.S)
		if len(res) <> 0:
			AlertKey=res[0]
		res=re.findall(r"Severity:(.*) Type",filecontent,re.S)
		if len(res) <> 0:
			Severity=res[0]
		res=re.findall(r"Type:(.*) Summary",filecontent,re.S)
		if len(res) <> 0:
			Type=res[0]
		res=re.findall(r"Summary:(.*)$",filecontent,re.S)
		if len(res) <> 0:
			Summary=res[0]
			try:
				Summary=Summary.decode('utf8').encode('gbk')
				#Summary=Summary
			except:
				pass
			
		strs=lc_libs.lc_gen_alert(ServerName,Node,AlertGroup,AlertKey,Severity,Type,Summary)
		#db.update_eventsdb_rt(agent_hostname,Node,AlertGroup,AlertKey,Severity,Type,Summary,logfile)
		
		#更新事件库
		Identifier = Node + " " + AlertGroup + " " + AlertKey + " " + Severity + " " + Type
		now =  int(time.time())
		#cur.execute("select Tally from alerts.status where Identifier = \'" + str(Identifier) + "\'")
		#res=cur.fetchall()
		res=LCSybase_count(Identifier)
		if int(res) == 0:
			#res=res[0][0]
			res=int(res)+1
			strs="insert into alerts.status(Identifier,Node,NodeAlias,Manager,Agent,Summary,AlertGroup,AlertKey,Severity,OriginalSeverity,Type,OwnerUID,FirstOccurrence,LastOccurrence) values('" + Identifier + "','" + Node + "','" + Node + "','LightCamProbe','LightCam','" + Summary + "','" + AlertGroup + "','" + AlertKey + "'," + str(Severity)+","+str(Severity)+","+str(Type)+","+str(65534)+","+str(now)+","+str(now)+")"
		else:
			strs="update alerts.status set Summary=\'"+str(Summary)+"\',LastOccurrence="+str(now)+",Tally="+str(res)+",Severity="+str(Severity)+" where Identifier = \'" + str(Identifier) + "\'"
		try:
			#cur.execute(strs)
			print strs
			res=LCSybase_update(strs)
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" "+excinfo+"\n")
			logfile.flush()
		
		#等待
		time.sleep(1)

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	#pool = multiprocessing.Pool(processes=1)
	result = []



	agent_hostname=lc_libs.lc_gethostname()
	ServerName="LCS"
	SyslogFile="/var/log/lclog"

	for line in open(confname):
		if line[0] == '#':
			continue
		if "ServerName" in line:
			ServerName=line.strip('\n').split(":")[1]
		if "SyslogFile" in line:
			SyslogFile=line.strip('\n').split(":")[1]
			
	isql='/opt/sybase/OCS-15_0/bin/isql -SNETCOOL -U root -P '

	while True:
		try:	
			
			func(ServerName,SyslogFile)
			
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
			exit(0)
		time.sleep(1)
